package com.aierkeji.call.cms.service;

import java.util.Map;
import java.util.Optional;

import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.aierkeji.call.cms.contants.Contants;
import com.aierkeji.call.cms.dao.jpa.AkjCallClueFileDao;
import com.aierkeji.call.cms.entity.AkjCallClueFile;
import com.aierkeji.call.cms.entity.AkjCallUser;
import com.aierkeji.call.cms.util.DynamicSpecifications;
import com.aierkeji.call.cms.util.PageUtils;
import com.aierkeji.call.cms.util.ResultMapHelper;
import com.aierkeji.call.cms.util.SearchFilter;

@Service
public class AkjCallClueHistoryService {

	@Autowired
	AkjCallClueFileDao akjCallClueFileDao;

	public Map<String, Object> query(int pageNo, Map<String, Object> map) {
		Subject subject = SecurityUtils.getSubject();
		AkjCallUser akjCallUser = (AkjCallUser) subject.getSession().getAttribute("loginUser");
		map.put("EQ_userId", akjCallUser.getId());
		map.put("EQ_isDelete", false);
		Map<String, SearchFilter> filters = SearchFilter.parse(map);
		Specification<AkjCallClueFile> specs = DynamicSpecifications.bySearchFilter(filters.values(),
				AkjCallClueFile.class);
		Sort sort = Sort.by(Sort.Order.desc("backupsDate"), Sort.Order.desc("sequence"));
		PageRequest pageRequest = PageUtils.buildPageRequest(pageNo, Contants.PAGE_SIZE, sort);
		Page<AkjCallClueFile> page = this.akjCallClueFileDao.findAll(specs, pageRequest);
		return ResultMapHelper.success(page);
	}

	@Transactional
	public Map<String, Object> delete(long id) {
		// TODO Auto-generated method stub
		Optional<AkjCallClueFile> optional = this.akjCallClueFileDao.findById(id);
		if (optional.isPresent()) {
			AkjCallClueFile akjCallClueFile = optional.get();
			Subject subject = SecurityUtils.getSubject();
			AkjCallUser akjCallUser = (AkjCallUser) subject.getSession().getAttribute("loginUser");
			if (akjCallUser.getId().equals(akjCallClueFile.getUserId())) {
				akjCallClueFile.setIsDelete(true);
				this.akjCallClueFileDao.save(akjCallClueFile);
			}else {
				return ResultMapHelper.failure("没有权限删除文件！");
			}
		}else {
			return ResultMapHelper.nullParamsResult();
		}
		return ResultMapHelper.success();
	}

}
